package com.sinsz.wxpn;

import com.sinsz.wxpn.open.base.impl.BaseServiceImpl;
import com.sinsz.wxpn.open.menu.impl.MenuServiceImpl;
import com.sinsz.wxpn.open.message.impl.*;
import com.sinsz.wxpn.properties.WxpnProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletResponse;

/**
 * 微信公众号配置入口
 * @author chenjianbo
 */
@Configuration
@EnableConfigurationProperties({WxpnProperties.class})
@ComponentScan({"com.sinsz.wxpn"})
public class WxpnAutoConfiguration implements CommandLineRunner {

    private final WxpnProperties properties;

    private final ApplicationContext applicationContext;

    private final HttpServletResponse response;

    @Autowired(required = false)
    public WxpnAutoConfiguration(WxpnProperties properties,
                                 ApplicationContext applicationContext,
                                 HttpServletResponse response) {
        this.properties = properties;
        this.applicationContext = applicationContext;
        this.response = response;
    }

    /**
     * 创建微信公众号接口调用实例
     * @return
     */
    @Bean
    public WxpnBean wxpnBean() {
        return new WxpnBean.Builder()
                .setContext(applicationContext)
                .setAccept(new AcceptServiceImpl(properties))
                .setReply(new ReplyServiceImpl(properties))
                .setHandler(properties.getAesClass())
                .setBase(new BaseServiceImpl(properties, response))
                .setMenu(new MenuServiceImpl(properties))
                .setTemplate(new TemplateMessageServiceImpl(properties))
                .build();
    }

    /**
     * 创建微信公众号消息加解密实例
     * @return
     */
    @Bean
    public WxpnCryptBean wxpnCryptBean() {
        return new WxpnCryptBean(
                properties.getAesToken(),
                properties.getAppId(),
                properties.getAesKey());
    }

    @Override
    public void run(String... args) {
        SpringContext.init(wxpnBean().getContext());
    }
}
